<template>
	<view class="contents">
		<u-navbar :bgColor="bgColor">
			<view class="u-nav-slot nav-left" slot="left">
				<u-icon color="#ffffff" name="home" @click="goHome()" size="20"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="list" @click="$refs.menu.open()" color="#ffffff" size="19"></u-icon>
			</view>
			<view class="u-nav-slot" slot="right">
				<picker @change="bindPickerChange" :value="index" :range="dropdownsLists">
					<view class="uni-input">{{gptName}}</view>
				</picker>
			</view>
		</u-navbar>
		<scroll-view class="scroll-view" :style="{height:scrollViewHeight+'px'}" :scroll-y="true" :scroll-top="scrollTop"
			:scroll-with-animation="true">
			<view id="scroll-view-content" class="chat_rights">
				<template v-if="chatList && chatList.length > 0">
					<view v-for="(item,index) in chatList" :key="index" class="m-item">
						<view v-if="item.role === 'user'">
							<view class="item_user">
								<view class="chat_items">
									<view class="times">
										<span>{{ item.time }}</span>
									</view>
									{{ item.content }}
								</view>
								<view class="chat_tx">
									<img :src="avatar?avatar:require('@/static/tx.png')"
										style="width:40px;height:40px;border-radius: 40px;" />
								</view>
							</view>
						</view>
						<view v-if="item.role == 'assistant'">
							<view v-if="item.content" class="item_assistant">
								<view class="chat_tx">
									<img :src="clientLogo?clientLogo:'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'"
										style="width:40px;height:40px;border-radius: 40px;" />
								</view>
								<view class="chat_items">
									<view class="times">
										<span>{{ item.time }}</span>
									</view>
									<view>
										<uaMarked :source="item.content"></uaMarked>
									</view>
								</view>
							</view>
						</view>

					</view>
				</template>
				<template v-else>
					<view class="tag_bq_box">
						<view class="tag_bq_title" style="margin-top: 30px;text-align: center;">
							请输入想问的问题
						</view>
					</view>
				</template>

			</view>
		</scroll-view>
		<view class="input_box">
			<textarea maxlength="-1" :disabled="disabled" confirm-type="send" @confirm="sendChat" v-model="form.sendText"
				style="width: calc(90% - 40upx);border-radius: 10upx; height:120upx;background: #e9e9e9;color: #333333;padding: 0 20upx;"
				placeholder="请输入..." rows="2"></textarea>
			<text class="el-icon-s-promotion" @click="sendChats(form.sendText)"
				style="font-size: 40upx;color:#ffffff;margin-left: 20upx;"></text>
		</view>
		<Scoket @onMessage="onMessage" ref="scoket"></Scoket>
		<Menus :addMenu="true" ref="menu" @clearItem="clearItem" @confirm="confirm" @changeChat="changeChat"
			@addChat="addChat" :chatsList="chatsList"></Menus>
	</view>
</template>

<script>
	import uaMarked from '@/components/ua2-markdown/ua-markdown.vue'
	import Scoket from '@/components/sse/scoket/scoket.vue'
	import Menus from '@/components/menus/menus.vue'
	export default {
		components: {
			uaMarked,
			Scoket,
			Menus
		},
		data() {
			return {
				form: {

				},
				scrollTop: 0, //滚动条位置
				scrollViewHeight: 576, //滚动视图的高度
				bgColor: '#000000',
				disabled: false,
				clientLogo: '',
				isAndroid: false,
				isiOS: false,
				index: 0,
				isActive: 0,
				isOpenGpt: 3,
				show: false,
				gptType: 1,
				times: '',
				gptName: '3.5',
				dropdownsList: [],
				dropdownsLists: [],
				gptRoleList: [],
				chatsList: [],
				chatList: [],
				avatar: "",
				timer: null,
				arr: [],
				tishi: false,
				sendNum: 0,
				scrollTop: 0,
				logId:null
			}
		},
		onLoad() {},
		onShow() {
			this.getBanben()
			this.avatar = JSON.parse(uni.getStorageSync('userInfo')).avatar
			this.getUserInfo()
		},
		watch: {
			arr: {
				handler(val) {
					if (val) {
						this.getTimes()
						const num = this.chatList.length - 1
						
						this.chatList[num].content = `${val.join('')}`
						this.chatList[num].time = this.times
							
						this.scrollToBottom()
					} else {
						this.getUserInfo(this.gptType)
					}
				},
				deep: true
			}
		},
		created() {
			if (uni.getStorageSync('scoket') && uni.getStorageSync('scoket') == 2) {
				this.$refs.scoket.initScokets()
				setTimeout(() => {
					location.reload();
				}, 100)
			}
		},
		mounted() {
			setTimeout(() => {
				// location.reload();
				this.scrollToBottom(); //调用滚动到底部的方法
			}, 100)
		},
		methods: {
			changeChat(data) {
				this.chatList = []
				console.log(data)
				if (this.chatsList && this.chatsList.length > 0) {
					this.chatList = this.chatsList[data].contents
					this.logId = this.chatsList[data].id
				}
				this.scrollToBottom()
				console.log('changeChat')
			},
			scrollToBottom() {
				setTimeout(() => {
					uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
						let top = res.height - this.scrollViewHeight + 80;
						if (top > 0) {
							this.scrollTop = top;
						}
					}).exec()
				}, 500)
			},
			goHome() {
				uni.reLaunch({
					url: '/pages/home/home'
				})
			},
			goback() {
				uni.switchTab({
					url: '/pages/gptpic/gptpic'
				})
			},
			onScroll(e) {
				console.log(e.detail.scrollTop)
				this.scrollTop = e.detail.scrollTop + 9999
			},
			addChat(index) {
				if (this.chatsList.length > 0 && this.chatsList[0].contents.length === 0) {
					this.$message.error('存在未完成的对话，不可新建')
				} else {
					const obj = {
						title: '新建对话',
						sendType: index,
						contents: []
					}
					this.chatsList.unshift(obj)
					this.chatList = []
					this.logId = null
					console.log('addChat')
				}
			},
			confirm(datas) {
				if (datas.id) {
					this.https('/ai/gpt/delLog', {
						logId: datas.id
					}).then(res => {
						if (res.code == 200) {
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/white/white'
								})
							}, 500)
							this.chatsList = this.chatsList.filter(item=>{
								return item.id!=datas.id
							})
							this.chatList = []
							this.logId = null
						}
					})
				} else {
					this.chatLists.splice(0, 1)
				}
			},
			clearItem(data) {
				
			},
			getBanben() {
				this.dropdownsLists = ['GPT 3.5', 'GPT 4.0']
				this.dropdownsList = [
					{id:1,value:3,name:'3.5'},
					{id:2,value:3,name:'4.0'},
				]
			},
			judge() {
				var u = navigator.userAgent
				this.isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
				this.isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
			},
			bindPickerChange(e) {
				this.gptName = this.dropdownsList[e.target.value].name
				this.gptType = this.dropdownsList[e.target.value].id
				// this.getUserInfo(this.gptType)
			},
			getUserInfo(index) {
				this.https('/ai/gpt/getMessageLog?pageSize=9999',{},{
					Authorization:'Bearer '+uni.getStorageSync('token'),
					},'get').then(res=>{
						console.log(res)
						this.chatsList = res.rows
						this.scrollToBottom()
						this.chatsList.map(item => {
							this.$set(item, 'contents', JSON.parse(item.useValue))
							this.$set(item, 'title', JSON.parse(item.useValue)[0].content)
						})
					})
			},
			chatSend(text) {
				this.sendNum ++
				this.getTimes()
				const that = this
				this.disabled = true
				const obj = {
					content: text, // 获取发送文本框中的内容
					role: 'user',
					time: that.times
				}
				if (this.chatsList.length > 0 && this.chatsList[0].contents.length === 0) {
					if (that.sendNum == 1) {
						this.chatsList[0].title = text
						this.chatsList[0].contents.push(obj)
						this.chatList = this.chatsList[0].contents

						that.sendMessage(that.chatList)
					} else {
						uni.showToast({
							title: '请勿重复提交',
							icon: 'error'
						})
					}
				} else if (this.chatsList.length === 0) {
					if (that.sendNum == 1) {
						const os = {}
						os.title = text
						os.contents = []
						os.sendType = this.gptType
						os.contents.push(obj)
						this.chatsList.push(os)
						this.chatList = os.contents
						that.sendMessage(that.chatList)
					} else {
						uni.showToast({
							title: '请勿重复提交',
							icon: 'error'
						})
					}
				} else {
					if (that.sendNum == 1) {
						this.chatsList[this.isActive].contents.push(obj)
						that.sendMessage(that.chatList)
					} else {
						uni.showToast({
							title: '请勿重复提交',
							icon: 'error'
						})
					}
				}
			},
			sendChats(texts) {
				this.sendNum++
				this.getTimes()
				const that = this
				if (texts) {
					const text = texts.replace(this.emojiRegex, '')
					this.disabled = true
					const obj = {
						content: text, // 获取发送文本框中的内容
						role: 'user',
						time: that.times
					}
					if (this.chatsList.length > 0 && this.chatsList[0].contents.length === 0) {

						if (that.sendNum == 1) {
							this.chatsList[0].title = text
							this.chatsList[0].contents.push(obj)
							this.chatList = this.chatsList[0].contents
							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}
					} else if (this.chatsList.length === 0) {
						if (that.sendNum == 1) {
							const os = {}
							os.title = text
							os.contents = []
							os.sendType = this.gptType
							os.contents.push(obj)
							this.chatsList.push(os)
							this.chatList = os.contents

							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}
					} else {
						if (this.sendNum == 1) {
							this.chatsList[this.isActive].contents.push(obj)

							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}
					}
				} else {
					uni.showToast({
						title: '请输入',
						icon: 'error'
					})
				}
			},
			sendChat(event) {
				this.sendNum++
				this.getTimes()
				const texts = event.target.value
				const that = this
				if (texts) {
					const text = texts.replace(this.emojiRegex, '')
					this.disabled = true
					const obj = {
						content: text, // 获取发送文本框中的内容
						role: 'user',
						time: that.times,
					}
					if (that.chatsList.length > 0 && that.chatsList[0].contents.length === 0) {
						if (that.sendNum == 1) {
						that.chatsList[0].title = text
						that.chatsList[0].contents.push(obj)
						that.chatList = that.chatsList[0].contents
						
							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}

					} else if (that.chatsList.length === 0) {
						if (that.sendNum == 1) {
						const os = {}
						os.title = text
						os.contents = []
						os.sendType = that.gptType
						os.contents.push(obj)
						that.chatsList.push(os)
						that.chatList = os.contents
						
							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}
					} else {
						if (that.sendNum == 1) {
						that.chatsList[that.isActive].contents.push(obj)
						
							that.sendMessage(that.chatList)
						} else {
							uni.showToast({
								title: '请勿重复提交',
								icon: 'error'
							})
						}
					}
				}else{
					uni.showToast({
						title: '请输入',
						icon: 'error'
					})
				}
			},
			getTimes() {
				const date = new Date()
				const yyyy = date.getFullYear()
				const m = date.getMonth() + 1
				const mm = m < 10 ? `0${m}` : `${m}`
				const d = date.getDate()
				const dd = d < 10 ? `0${d}` : `${d}`
				const h = date.getHours()
				const hh = h < 10 ? `0${h}` : h
				const ms = date.getMinutes()
				const mn = ms < 10 ? `0${ms}` : `${ms}`
				const s = date.getSeconds()
				const ss = s < 10 ? `0${s}` : `${s}`
				this.times = `${yyyy}-${mm}-${dd} ${hh}:${mn}:${ss}`
			},
			sendMessage(message) {
				// if (message.length > 1) {
				// 	logId = message[message.length - 2].logId
				// }
				console.log(message)
				// return false

				const obj = {
					// problem: message[message.length - 1].content,
					logId: this.logId,
					type: this.gptType == '1' ? 3 : 4,
					userId:uni.getStorageSync('userId'),
					nickname:uni.getStorageSync('userInfo').nickName,
					message:message[message.length-1]
				}
				
				
				this.https('/ai/gpt/chat', obj)
					.then(res => {
						if (res.code == 200) {
							this.arr = []
							this.form.sendText = ''
							
							this.logId = res.data
							
							uni.setStorageSync('SET_MESSAGES', this.chatsList)
							this.getdaoTimes(1)
						} else {
							this.disabled = false
						}
						setTimeout(() => {
							this.sendNum = 0 // 2 秒后将 sendNum 属性设置为 0
						}, 500)
					})
					.catch(() => {
						this.disabled = false
					})
			},
			getdaoTimes(TIME_COUNT) {
				this.tishi = false
				if (!this.timer) {
					let code = TIME_COUNT
					this.timer = setInterval(() => {
						if (code > 0 && code <= TIME_COUNT) {
							code--
							if (code == 0) {
								this.tishi = true
							}
						} else {
							clearInterval(this.timer)
							this.timer = null
						}
					}, 1000)
				}
			},
			onMessage(message) {
				console.log(message)
				if(this.chatList[this.chatList.length-1].role=='user'){
					const gpt = {
						content: '', // 获取发送文本框中的内容
						role: 'assistant',
						times: '',
						// logId: res.data
					}
					this.chatList.push(gpt)
				}
				if(message!='[DONE]'){
					message = JSON.parse(message)
					
					console.log(123)
					if(message.hasOwnProperty('error')){
						const msg = message.error.message
						console.log(msg)
						this.arr.push(msg)
						// this.https('/ai/gpt/saveMssageLog/'+this.logId,this.chatList[this.chatList.length-1]).then(res=>{
						// 	this.disabled = false
						// 	// this.getUserInfo(this.activeName)
						// 	this.tishi = false
						// })
						console.log(this.chatList)
					}else{
						// console.log('监听的消息',message)
						const msg = message.choices[0].delta.content
						this.arr.push(msg)
					}
					
				}else{
					this.https('/ai/gpt/saveMssageLog/'+this.logId,this.chatList[this.chatList.length-1]).then(res=>{
						this.disabled = false
						// this.getUserInfo(this.activeName)
						this.tishi = false
					})
					
					
				}
				
			}
		},
		onUnload() {
			console.log(12)
			this.chatsList = []
			this.$refs.scoket.closeScoket()
			// 页面销毁时关闭Socket连接
		}
	}
</script>

<style lang="scss" scoped>
	.contents {
		overflow-y: hidden;
		padding: 30upx;

		.tag_bq_box {
			margin-top: 100upx;

			.tag_bq_title {
				font-size: 36upx;
				color: #1989fa;
			}

			.tags_box {
				overflow: hidden;
				text-align: center;
				margin-top: 20upx;

				.tags_item {
					display: inline-block;
					margin: 10upx;
					text-align: center;
					background: linear-gradient(to right, rgba(66, 83, 216, .5), rgba(213, 51, 186, .3));
					border-radius: 10upx;
					color: #d9d9d9;
					padding: 5upx 10upx;
				}
			}
		}

		.scroll-view {
			padding-top: 80upx;
			height: calc(100vh - 290upx) !important;
		}

		.chat_rights {
			.item_user {
				display: flex;
				justify-content: flex-end;
				margin: 40upx 0;

				.chat_items {
					background: rgb(66, 83, 216);
					border-radius: 10upx;
					padding: 20upx;
					max-width: 100%;
					overflow-x: auto;
					margin-right: 20upx;
					color: #ffffff;

					.times {
						font-size: 24upx;
						color: #d9d9d9;
					}
				}
			}

			.item_assistant {
				display: flex;

				.chat_items {
					background: #333333;
					border-radius: 10upx;
					padding: 20upx;
					margin-left: 10px;
					overflow-x: auto;
					max-width: 100%;
					color: #ffffff;

					.times {
						font-size: 24upx;
						color: #d9d9d9;
					}
				}
			}
		}

		.input_box {
			background: #333333;
			margin-left: -30upx;
			margin-right: -30upx;
			padding: 20upx;
			overflow: hidden;
			height: 120upx;
			display: flex;
			align-items: center;
			margin-top: 20upx;
		}
	}
</style>
<style>
	.u-nav-slot {
		color: #ffffff;
	}

	.nav-left {
		display: flex;
		width: 160upx;
		border: 2upx solid #999999;
		border-radius: 60upx;
		height: 60upx;
		justify-content: center;
		align-items: center;
	}
</style>